<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author Cheng
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'maintenance:management:inContract:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>

    <BasicForm @register="registerForm" />
    <div v-if="resFileSrc" class="mt-2 id='downloadFile">
      <a-button @click="downloadFile(resFileSrc)" type="primary" >合同下载</a-button>
    </div>
    <template #footer>
      <Button  @click="closeDrawer">  <Icon icon="i-ant-design:close-outlined" />取消</Button>
      <Button type="primary" @click="openTaskFormModal"> <Icon icon="i-ant-design:file-text-outlined" />生成维保任务</Button>
      <Button type="primary" @click="handleSubmit"> <Icon icon="i-ant-design:check-outlined" />确认</Button>
    </template>
      <TaskForm  :record="inContractRecord"  @register="registerTaskFormModal" ></TaskForm>
  </BasicDrawer>
</template> 
<script lang="ts" setup name="ViewsMaintenanceManagementInContractForm">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicModal,useModal} from '/@/components/Modal';
  import { InContract, inContractSave, inContractForm } from '/@/api/maintenance.management/inContract';
  import { unitEnterpriseDominantListData } from '/@/api/unitmanage/unitEnterpriseDominant';
  import { officeTreeData } from '/@/api/sys/office';
  import { Button } from 'ant-design-vue';
  import { uploadFile, uploadFileList, uploadParams} from '/@/api/sys/upload';
  import TaskForm from './task.vue';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('maintenance.management.inContract');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<InContract>({} as InContract);
  const resFileSrc=ref()

  const fileUrl = ref<string>('');
  const bizKey = ref<string>('');
  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增维保合同') : t('编辑维保合同'),
  }));
  const EnterpriseParams = ref<Recordable>({
    name:''
  });
  const maintenanceEnterpriseParams = ref<Recordable>({
    name:'',
    dominantType:'maintenance'
  });

  const inContractRecord=ref<Object>({});

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('合同名称'),
      field: 'name',
      component: 'Input',
      componentProps: {
        maxlength: 255,
      },
    },
    {
      label: t('维保单位'),
      field: 'benterpriseId',
      fieldLabel: 'benterpriseName',
      component: 'Select',
      componentProps: () => {
        return {
          api: unitEnterpriseDominantListData,
          params: maintenanceEnterpriseParams.value,
          fieldNames: { label: 'name', value: 'unitCode' },
          resultField: 'list',
          notFoundContent: '未查询到记录',
          filterTreeNode: false,
          allowClear: true,
          filterOption: false,
          immediate: true,
          onSearch: (value: string) => {
            maintenanceEnterpriseParams.value.name = value;
            console.log(maintenanceEnterpriseParams.value);
          },
        };
      },
    },
    {
      label: t('业主单位'),
      field: 'aenterpriseId',
      fieldLabel: 'aenterpriseName',
      component: 'Select',
      componentProps: () => {
        return {
          placeholder: t('请输入业主企业'),
          api: unitEnterpriseDominantListData,
          params: EnterpriseParams.value,
          fieldNames: { label: 'name', value: 'unitCode' },
          resultField: 'list',
          notFoundContent: '未查询到记录',
          filterTreeNode: false,
          allowClear: true,
          filterOption: false,
          immediate: true,
          onSearch: (value: string) => {
            EnterpriseParams.value.name = value;
            console.log(EnterpriseParams.value);
          },
        };
      },
    },
    {
      label: t('合同起始年月'),
      field: 'startDate',
      component: 'DatePicker',
      componentProps: {
        maxlength: 255,
        format: 'YYYY-MM-DD',
      },
    },
    {
      label: t('合同结束年月'),
      field: 'endDate',
      component: 'DatePicker',
      componentProps: {
        maxlength: 255,
        format: 'YYYY-MM-DD',
      },
    },
    {
      label: t('合同状态'),
      field: 'state',
      component: 'Select',
      componentProps: {
        maxlength: 255,
        options: [
          { label: t('有效'), value: '有效' },
          { label: t('暂存'), value: '暂存' },
          { label: t('过期'), value: '过期' },

        ]
      },
    },
    {
      label: t('合同地址'),
      field: 'fileSrc',
      show:false,
      component: 'Input',
      componentProps: {
      },
    },
    {
      label: t('合同上传'),
      field: 'dataMap',
      component: 'Upload',
      componentProps: {      
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        fileUrl:computed(() => record.value.fileSrc),
        bizType: 'inContract_file',
        uploadType: 'all',
        maxNumber:1,
      },
      colProps: { md: 24, lg: 24 },
    },
  ];
  
 

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { md: 24, lg: 12 },
  });

  const [registerTaskFormModal, { openModal: openTaskFormModal }] = useModal();

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await inContractForm(data);
    resFileSrc.value=res.inContract.fileSrc
    console.log('res',res)
    inContractRecord.value=res.inContract
    console.log('inContractRecord',inContractRecord.value)
    console.log('res.inContract.fileSrc',res.inContract.fileSrc)
    record.value = (res.inContract || {}) as InContract;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setDrawerProps({ loading: false });
  });



  async function handleSubmit() {
    try {
      let data = await validate();
      // 添加 fileSrc 字段到 data 对象中
      data = { ...data, 
              fileSrc:(data.dataMap.inContract_fileUrl != null) ? (data.dataMap.inContract_fileUrl.split('?')[0]) : record.value.fileSrc, 
              fileSrcId:(data.dataMap.inContract_file != null) ? data.dataMap.inContract_file : record.value.fileSrcId
            };
      console.log('data.fileSrc',data.fileSrc)
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        // fileSrc: record.value.fileSrc,
        tid: record.value.tid,
      };
    //  console.log('fileSrc',params.fileSrc)
     console.log('record',record.value)
      const res = await inContractSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);


      console.log('data',data)

      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(error.message || t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }

   // 下载文件的函数
   function downloadFile(resFileSrc: string) {
    // console.log('resFileSrc',resFileSrc)
    resFileSrc = resFileSrc.split('?')[0];
    console.log('resFileSrc',resFileSrc)
    if (!resFileSrc) {
    showMessage(t('文件链接无效'));
    return;
  }
   // 创建一个 XMLHttpRequest 对象
   const xhr = new XMLHttpRequest();
  xhr.open('GET', resFileSrc, true);
  xhr.responseType = 'blob';

  xhr.onload = function () {
    if (xhr.status === 200) {
      const blob = xhr.response;
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = '文件名'; // 这里可以根据需要设置文件名
      link.click();
      URL.revokeObjectURL(link.href);
    } else {
      showMessage(t('下载失败'));
    }
  };

  xhr.onerror = function () {
    showMessage(t('下载失败'));
  };

  xhr.send();
}

  // // 预览文件的函数
  // function previewFile(resFileSrc: string) {
  //   window.open(resFileSrc, '_blank');
  // }
</script>
<style scoped lang="less">
 .mt-2{
  margin-left: 120px;
 }
</style>